package factory;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.Session;
import org.hibernate.service.ServiceRegistry;

public class HibernateSessionFactory {
    // 服务注册表
    private static ServiceRegistry serviceRegistry;
    // 会话工厂
    private static final SessionFactory sessionFactory;

    static {
        try {
            serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
            MetadataSources metadataSources = new MetadataSources(serviceRegistry);
            // 读取映射作为应用程序资源名称（即类路径查找）
            metadataSources.addResource("hibernate.cfg.xml");
            sessionFactory = metadataSources.buildMetadata().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        // 开启一个会话
        return sessionFactory.openSession();
    }
}
